<script setup>
import { ref, onMounted, computed } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import MapComponent from '../components/MapComponent.vue';
import { ElMessage } from "element-plus"; // 引入地图组件

const store = useStore();
const router = useRouter();

const userInfo = ref(null);
const orderOverview = ref({});
const recommendedLockers = ref([]); // 新增，存储推荐的快递柜数据
const lockers = ref([]); // 新增，存储从 Vuex 获取的快递柜数据
const orders = ref([]); // 存储用户订单数据

// 获取用户名
const userName = computed(() => store.getters.userInfo?.userName); // 从 Vuex 中获取用户名

// 跳转到智能推荐快递柜页面
const goToSmartLocker = () => {
  router.push('/smart/locker');
};

// 获取推荐快递柜数据
const fetchRecommendedLockers = () => {
  try {
    // 假设你有一个后端接口可以获取推荐的快递柜数据
    store.dispatch('fetchRecommendedLockers').then(response => {
      recommendedLockers.value = response.data.lockers;
    });
  } catch (error) {
    ElMessage.error({ message: '获取推荐快递柜失败', duration: 1000 });
    console.error('获取推荐快递柜失败', error);
  }
};

// 获取订单数据
const fetchOrders = () => {
  try {
    // 假设你有一个后端接口可以获取订单数据
    store.dispatch('fetchOrders').then(response => {
      orders.value = response.data.orders;
    });
  } catch (error) {
    ElMessage.error({ message: '获取订单数据失败', duration: 1000 });
    console.error('获取订单数据失败', error);
  }
};

// 取消订单
const cancelOrder = (orderId) => {
  try {
    // 假设你有一个后端接口可以取消订单
    store.dispatch('cancelOrder', orderId).then(() => {
      ElMessage.success({ message: '订单取消成功', duration: 1000 });
      fetchOrders(); // 刷新订单列表
    });
  } catch (error) {
    ElMessage.error({ message: '订单取消失败', duration: 1000 });
    console.error('订单取消失败', error);
  }
};

// 模拟柜门控制
const controlLockerDoor = (lockerId, doorId) => {
  try {
    // 假设你有一个后端接口可以控制柜门
    store.dispatch('controlLockerDoor', { lockerId, doorId }).then(() => {
      ElMessage.success({ message: '柜门控制成功', duration: 1000 });
    });
  } catch (error) {
    ElMessage.error({ message: '柜门控制失败', duration: 1000 });
    console.error('柜门控制失败', error);
  }
};

// 生成取件码
const generatePickupCode = (orderId) => {
  try {
    // 假设你有一个后端接口可以生成取件码
    store.dispatch('generatePickupCode', orderId).then((response) => {
      ElMessage.success({ message: `取件码: ${response.data.pickupCode}`, duration: 1000 });
    });
  } catch (error) {
    ElMessage.error({ message: '取件码生成失败', duration: 1000 });
    console.error('取件码生成失败', error);
  }
};

// 验证取件码
const verifyPickupCode = (pickupCode) => {
  try {
    // 假设你有一个后端接口可以验证取件码
    store.dispatch('verifyPickupCode', pickupCode).then((response) => {
      if (response.data.valid) {
        ElMessage.success({ message: '取件码有效', duration: 1000 });
      } else {
        ElMessage.error({ message: '取件码无效', duration: 1000 });
      }
    });
  } catch (error) {
    ElMessage.error({ message: '取件码验证失败', duration: 1000 });
    console.error('取件码验证失败', error);
  }
};

// 路由跳转
const goToRoute = (route) => {
  router.push(route);
};

// 页面加载时获取用户信息和订单概览
onMounted(() => {
  store.dispatch('fetchUserInfo', userName.value).then(data => { // 确保传递了用户名
    userInfo.value = data;
  });
  store.dispatch('fetchOrderOverview').then(data => {
    orderOverview.value = data;
  });
  fetchRecommendedLockers(); // 加载推荐快递柜数据
  store.dispatch('fetchLockers').then(data => { // 获取快递柜数据
    lockers.value = data.lockers; // 从 Vuex 中获取快递柜数据
  });
  fetchOrders(); // 获取订单数据
});
</script>

<template>
  <div class="container">
    <div class="section">
      <h2>订单概览</h2>
      <ul class="overview-list">
        <li><span>已下单:</span> {{ orderOverview.placed || 0 }}</li>
        <li><span>已寄送:</span> {{ orderOverview.sent || 0 }}</li>
        <li><span>已取件:</span> {{ orderOverview.picked || 0 }}</li>
        <li><span>异常订单:</span> {{ orderOverview.exception || 0 }}</li>
      </ul>
    </div>

    <!-- 订单详情 -->
    <div class="section">
      <h2>我的订单</h2>
      <ul v-if="orders.length > 0" class="order-list">
        <li v-for="order in orders" :key="order.id" class="order-item">
          <p><strong>订单号:</strong> {{ order.orderNumber }}</p>
          <p><strong>状态:</strong> {{ order.status }}</p>
          <el-button @click="cancelOrder(order.id)" type="danger" v-if="order.status === 'placed'">取消订单</el-button>
          <el-button @click="generatePickupCode(order.id)" type="primary" v-if="order.status === 'sent'">生成取件码</el-button>
          <el-button @click="verifyPickupCode(order.pickupCode)" type="success" v-if="order.status === 'picked'">验证取件码</el-button>
        </li>
      </ul>
      <p v-else>暂无订单</p>
    </div>

    <!-- 智能推荐快递柜展示部分 -->
    <div class="section">
      <h2>智能推荐快递柜</h2>
      <ul v-if="recommendedLockers.length > 0" class="locker-list">
        <li v-for="locker in recommendedLockers" :key="locker.id" class="locker-item">
          <p><strong>快递柜名称:</strong> {{ locker.name }}</p>
          <p><strong>地址:</strong> {{ locker.address }}</p>
          <p><strong>距离:</strong> {{ locker.distance }} km</p>
          <el-button @click="goToRoute('/locker/details/' + locker.id)" type="primary">查看详情</el-button>
          <el-button @click="controlLockerDoor(locker.id, locker.doorId)" type="warning">控制柜门</el-button>
        </li>
      </ul>
      <p v-else>暂无推荐快递柜</p>
      <el-button @click="goToSmartLocker" type="primary">查看智能推荐快递柜</el-button>
    </div>

    <!-- 地图组件展示 -->
    <div class="section">
      <h2>附近快递柜位置</h2>
      <MapComponent :lockers="recommendedLockers"/> <!-- 传递推荐快递柜数据到地图组件 -->
    </div>
  </div>
</template>

<style scoped>
.container {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.section {
  width:1200px;
  margin: 0 auto;
  height: 100%;
  background-color: #f9fafb;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.overview-list, .order-list, .locker-list {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.overview-list li, .order-list li, .locker-list li {
  margin-bottom: 12px;
}

.order-item p, .locker-item p {
  margin: 4px 0;
}

.el-button {
  margin-top: 12px;
}
</style>



